package com.immunology.web;

import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.immunology.domain.User;
import com.immunology.exception.UserAlreadyExistException;
import com.immunology.service.security.UserSecurityService;

@Controller
public class RegistrationController {
	private static final Logger LOG = Logger.getLogger(RegistrationController.class);

	@Autowired
	private UserSecurityService securityService;

	@RequestMapping(value = "/registration", method = RequestMethod.POST)
	public ModelAndView registerUser(@ModelAttribute("user") @Valid User validUser, BindingResult bindingResult) {
		ModelAndView result = new ModelAndView("redirect:/index");
		if (bindingResult.hasErrors()) {
			result.setViewName("registration");
			return result;
		}
		try {
			LOG.info("Try to register User");
			securityService.registerUser(validUser);
		} catch (UserAlreadyExistException e) {
			String userExist = "User with login '" + validUser.getLogin()+ "' already exists.";
			LOG.error(userExist, e);
			result.setViewName("registration");
			result.addObject("error_register", userExist);
		}
		return result;
	}

	@RequestMapping(value = "registration", method = RequestMethod.GET)
	public String registerGet() {
		return "registration";
	}
}
